<template>
  <div 
  class="glass-nav sidebar flex-shrink-0 h-full"
  :class="{
    'w-64': !isCollapsed, 
    'w-12': isCollapsed,
    'theme-transition': true
  }"
>
    <div class="flex flex-col h-full">
      <!-- 折叠/展开按钮 -->
      <div class="absolute top-1/2 right-[-12px] transform -translate-y-1/2 z-20">
        <button @click="toggleCollapse"
          class="w-3 h-12 bg-blue-500/90 hover:bg-blue-500 rounded-r-md shadow-lg flex items-center justify-center text-white transition-all duration-300">
          <span v-if="isCollapsed">></span>
          <span v-else><</span>
        </button>
      </div>

      <!-- Logo -->
      <div class="p-6 border-b border-blue-500/30 flex-shrink-0" v-if="!isCollapsed">
        <div class="flex justify-between items-start">
          <div>
            <p class="text-2xl mt-1 font-bold" :class="themeState.isLight ? 'text-blue-600' : 'text-blue-400'">{{ ts('跨境政策咨询平台') }}</p>
          </div>
        </div>
      </div>
      <div class="p-4 border-b border-blue-500/30 flex-shrink-0" v-else>
        <div
          class="w-6 h-6 rounded-full bg-gradient-to-r from-electric-500 to-tech-blue-500 flex items-center justify-center mx-auto">
          <Globe class="w-5 h-5 text-white" />
        </div>
      </div>

      <!-- 用户信息 -->
      <div v-if="currentUser.isLoggedIn && !isCollapsed" class="p-4 border-b border-blue-500/30">
        <div class="flex items-center space-x-3 mb-3">
          <div
            class="w-10 h-10 rounded-full bg-gradient-to-r from-electric-500 to-tech-blue-500 flex items-center justify-center">
            <component :is="getUserIcon()" class="w-5 h-5 text-white" />
          </div>
          <div class="flex-1">
            <h3 class="font-medium text-sm" :class="themeState.isLight ? 'text-gray-900' : 'text-white'">{{ currentUser.name }}</h3>
            <p class="text-xs" :class="themeState.isLight ? 'text-blue-600' : 'text-blue-400'">{{ getUserTypeConfig().name }}</p>
          </div>
        </div>

        <!-- 快速切换按钮 -->
        <div class="grid grid-cols-2 gap-2">
          <button v-for="(config, type) in limitedUserTypes" :key="type" @click="quickSwitchUserType(type)" :class="[
            'px-2 py-1 rounded text-xs transition-colors border',
            currentUser.type === type
              ? 'bg-electric-500/20 text-electric-500 border-electric-500/50'
              : 'bg-white/5 text-white/70 border-white/20 hover:bg-white/10 hover:text-white'
          ]">
            {{ config.name.replace('用户', '').replace('角色', '') }}
          </button>
        </div>
      </div>
      <div v-else-if="currentUser.isLoggedIn && isCollapsed"
        class="p-2 border-b border-blue-500/30 flex justify-center">
        <div
          class="w-8 h-8 rounded-full bg-gradient-to-r from-electric-500 to-tech-blue-500 flex items-center justify-center">
          <component :is="getUserIcon()" class="w-4 h-4 text-white" />
        </div>
      </div>

      <!-- 未登录提示 -->
      <div v-else-if="!isCollapsed" class="p-4 border-b border-blue-500/30">
        <div class="text-center">
          <div class="w-10 h-10 rounded-full bg-gray-600 flex items-center justify-center mx-auto mb-2">
            <User class="w-5 h-5 text-gray-400" />
          </div>
          <p class="text-white/70 text-sm mb-2">{{ ts('未登录用户', '未登录用户') }}</p>
          <button @click="showUserDemo"
            class="w-full px-3 py-1 bg-electric-500/20 text-electric-500 rounded text-xs hover:bg-electric-500/30 transition-colors">
            {{ ts('体验不同用户', '体验不同用户') }}
          </button>
        </div>
      </div>
      <div v-else class="p-2 border-b border-blue-500/30 flex justify-center">
        <div class="w-8 h-8 rounded-full bg-gray-600 flex items-center justify-center">
          <User class="w-4 h-4 text-gray-400" />
        </div>
      </div>

      <!-- 导航菜单 -->
      <nav class="flex-1 p-2 overflow-y-auto">
        <template v-for="item in menuItems" :key="item.path || item.name">
          <!-- 普通菜单项 -->
          <router-link
            v-if="item.path"
            :to="item.path"
            :class="[
              'flex items-center px-3 py-3 rounded-lg transition-all duration-300 mb-1',
              isCollapsed ? 'justify-center' : 'space-x-3',
              $route.path === item.path 
                ? (themeState.isLight ? 'bg-blue-100 text-blue-700 border border-blue-200' : 'bg-blue-500/20 text-blue-400 cyber-glow border border-blue-500/30')
                : (themeState.isLight ? 'text-gray-600 hover:bg-gray-100 hover:text-gray-800' : 'text-white/70 hover:bg-white/10 hover:text-white')
            ]"
          >
            <component :is="item.icon" class="w-5 h-5 flex-shrink-0" />
            <span class="font-medium" v-if="!isCollapsed">{{ ts(item.name) }}</span>
          </router-link>

          <!-- 分组菜单项 -->
          <div v-else class="space-y-1 mb-1 relative">
            <button
              @click="isCollapsed ? showSubMenu(item, $event) : toggleGroup(item.name)"
              @mouseenter="isCollapsed ? showSubMenu(item, $event) : null"
              @mouseleave="isCollapsed ? hideSubMenuDelayed() : null"
              :class="[
                'flex items-center w-full px-3 py-3 rounded-lg transition-all duration-300',
                isCollapsed ? 'justify-center' : 'justify-between',
                themeState.isLight ? 'text-gray-600 hover:bg-gray-100 hover:text-gray-800' : 'text-white/70 hover:bg-white/10 hover:text-white'
              ]"
            >
              <div :class="['flex items-center', isCollapsed ? '' : 'space-x-3']">
                <component :is="item.icon" class="w-5 h-5 flex-shrink-0" />
                <span class="font-medium" v-if="!isCollapsed">{{ ts(item.name) }}</span>
              </div>
              <ChevronDown 
                v-if="!isCollapsed"
                :class="[
                  'w-4 h-4 transition-transform duration-300',
                  expandedGroups[item.name] ? 'rotate-180' : ''
                ]" 
              />
            </button>
            
            <!-- 子菜单 -->
            <div 
              v-show="expandedGroups[item.name] && !isCollapsed"
              class="ml-4 space-y-1 border-l pl-4"
              :class="themeState.isLight ? 'border-gray-300' : 'border-white/20'"
            >
              <router-link
                v-for="child in item.children"
                :key="child.path"
                :to="child.path"
                :class="[
                  'flex items-center space-x-3 px-3 py-2 rounded-lg transition-all duration-300',
                  isChildRouteActive(child.path)
                    ? (themeState.isLight ? 'bg-blue-100 text-blue-700 border border-blue-200' : 'bg-blue-500/20 text-blue-400 cyber-glow border border-blue-500/30')
                    : (themeState.isLight ? 'text-gray-600 hover:bg-gray-50 hover:text-gray-800' : 'text-white/60 hover:bg-white/5 hover:text-white/80')
                ]"
              >
                <component :is="child.icon" class="w-4 h-4" />
                <span class="text-sm">{{ ts(child.name) }}</span>
              </router-link>
            </div>
          </div>
        </template>
      </nav>

      <!-- 底部信息 -->
      <div class="p-4 border-t flex-shrink-0" :class="themeState.isLight ? 'border-gray-200' : 'border-blue-500/30'" v-if="!isCollapsed">
        <div class="text-center text-sm">
          <p :class="themeState.isLight ? 'text-gray-600' : 'text-white/60'">© 2024 {{ ts('跨境政策咨询平台') }}</p>
          <p class="mt-1" :class="themeState.isLight ? 'text-blue-600' : 'text-blue-400'">{{ ts('版权所有·保留一切权利') }}</p>
        </div>
      </div>
      <div class="p-2 border-t flex-shrink-0" :class="themeState.isLight ? 'border-gray-200' : 'border-blue-500/30'" v-else>
        <div class="text-center text-xs" :class="themeState.isLight ? 'text-gray-600' : 'text-white/60'">
          <p>© 2024</p>
        </div>
      </div>
    </div>
  </div>

  <!-- 使用 Teleport 将悬浮子菜单渲染到 body 中，确保不被父元素限制 -->
  <Teleport to="body">
    <div 
      v-if="isCollapsed && activeSubMenu"
      @mouseenter="clearHideTimer"
      @mouseleave="hideSubMenuDelayed"
      class="fixed w-48 z-[99999] glass-card rounded-lg shadow-lg py-2"
      :class="themeState.isLight ? 'bg-white border-gray-200' : 'bg-gray-800/95 border-gray-700'"
      :style="subMenuPosition"
    >
      <div class="px-3 py-2 border-b" :class="themeState.isLight ? 'border-gray-200' : 'border-gray-700'">
        <div class="flex items-center space-x-2">
          <component :is="menuItems.find(item => item.name === activeSubMenu)?.icon" class="w-4 h-4" :class="themeState.isLight ? 'text-blue-600' : 'text-blue-400'" />
          <span class="text-sm font-medium" :class="themeState.isLight ? 'text-gray-900' : 'text-white'">{{ ts(activeSubMenu) }}</span>
        </div>
      </div>
      <router-link
        v-for="child in menuItems.find(item => item.name === activeSubMenu)?.children"
        :key="child.path"
        :to="child.path"
        @click="hideSubMenu"
        class="block px-3 py-2 text-sm hover:bg-opacity-10 transition-colors"
        :class="[
          themeState.isLight 
            ? 'text-gray-700 hover:bg-blue-600 hover:text-blue-600' 
            : 'text-gray-300 hover:bg-blue-400 hover:text-blue-400'
        ]"
      >
        {{ ts(child.name) }}
      </router-link>
    </div>
  </Teleport>
</template>

<script>
import {
  BarChart3,
  MessageSquare,
  FileText,
  Bell,
  Calendar,
  Search,
  GitCompare,
  Target,
  MapPin,
  User,
  Globe,
  TrendingUp,
  Building,
  Shield,
  GraduationCap,
  ChevronDown,
  Calculator
} from 'lucide-vue-next'
import { useTranslation } from '../composables/useTranslation.js'
import { currentUser, userService, USER_TYPES, userTypeConfigs } from '../services/userService.js'
import { themeState } from '../services/themeService.js'
import { ref } from 'vue'
import { useRoute } from 'vue-router'

export default {
  name: 'Sidebar',
  components: {
    BarChart3,
    MessageSquare,
    FileText,
    Bell,
    Calendar,
    Search,
    GitCompare,
    Target,
    MapPin,
    User,
    Globe,
    TrendingUp,
    Building,
    Shield,
    GraduationCap,
    ChevronDown,
    Calculator
  },
  setup() {
    // 使用翻译系统
    const { ts } = useTranslation()
    const route = useRoute()

    // 折叠状态
    const isCollapsed = ref(false)
    
    // 悬浮子菜单状态
    const activeSubMenu = ref(null)
    const subMenuPosition = ref({ left: 0, top: 0 })
    let hideTimer = null

    const menuItems = [
      { path: '/', name: '全球政策概览', icon: 'BarChart3' },
      { path: '/ai-chat', name: '🤖 AI智能咨询', icon: 'MessageSquare' },
      { path: '/digital-human', name: '👤 数字人', icon: 'User' },
      { 
        name: '📋 政策工具', 
        icon: 'FileText',
        children: [
          { path: '/policy-center?tab=analysis', name: '智能分析', icon: 'Target' },
          { path: '/policy-center?tab=search', name: '政策查询', icon: 'Search' },
          { path: '/policy-center?tab=compare', name: '政策对比', icon: 'GitCompare' },
          { path: '/policy-center?tab=simulation', name: '政策推演', icon: 'TrendingUp' },
          { path: '/policy-center?tab=tax-analysis', name: '税收政策分析', icon: 'Calculator' },
          { path: 'policy-center?tab=trace', name: '政策溯源', icon: 'Globe' }
        ]
      },
      { path: '/region-compare', name: '🌏 跨境对比', icon: 'GitCompare' },
      { 
        name: '🔔 消息中心', 
        icon: 'Bell',
        children: [
          { path: '/policy-push', name: '政策推送', icon: 'Bell' },
          { path: '/reminders', name: '定时提醒', icon: 'Calendar' },
        ]
      },
      { path: '/user-center', name: '👤 个人中心', icon: 'User' },
    ]

    // 限制显示的用户类型（用于快速切换）
    const limitedUserTypes = {
      [USER_TYPES.INDIVIDUAL]: userTypeConfigs[USER_TYPES.INDIVIDUAL],
      [USER_TYPES.ENTERPRISE]: userTypeConfigs[USER_TYPES.ENTERPRISE],
      [USER_TYPES.GOVERNMENT]: userTypeConfigs[USER_TYPES.GOVERNMENT],
      [USER_TYPES.ACADEMIC]: userTypeConfigs[USER_TYPES.ACADEMIC]
    }

    // 获取用户类型配置
    const getUserTypeConfig = () => {
      return userService.getUserTypeConfig()
    }

    // 获取用户图标
    const getUserIcon = () => {
      const iconMap = {
        [USER_TYPES.ENTERPRISE]: Building,
        [USER_TYPES.INDIVIDUAL]: User,
        [USER_TYPES.GOVERNMENT]: Shield,
        [USER_TYPES.ACADEMIC]: GraduationCap
      }
      return iconMap[currentUser.type] || User
    }

    // 快速切换用户类型
    const quickSwitchUserType = (type) => {
      if (userService.switchUserType(type)) {
        window.location.reload()
      }
    }

    // 显示用户演示
    const showUserDemo = () => {
      // 演示登录为个人用户
      const mockData = userService.getMockUserData(USER_TYPES.INDIVIDUAL)
      userService.login(mockData)
      window.location.reload()
    }


    // 自动初始化所有分组的展开状态（有children的菜单项）
    const expandedGroups = ref({})
    menuItems.forEach(item => {
      if (item.children) {
        expandedGroups.value[item.name] = false
      }
    })

    // 切换分组展开状态，支持任意分组
    const toggleGroup = (groupName) => {
      expandedGroups.value[groupName] = !expandedGroups.value[groupName]
    }

    // 判断子菜单是否为当前活动路由
    const isChildRouteActive = (childPath) => {
      // 解析链接中的路径和查询参数
      const [path, queryString] = childPath.split('?')
      const currentPath = route.path
      
      // 如果路径不匹配，直接返回false
      if (path !== currentPath) {
        return false
      }
      
      // 如果有查询参数，需要检查tab参数是否匹配
      if (queryString) {
        const urlParams = new URLSearchParams(queryString)
        const tabParam = urlParams.get('tab')
        return route.query.tab === tabParam
      }
      
      // 如果没有查询参数，只比较路径
      return true
    }

    // 切换折叠状态
    const toggleCollapse = () => {
      isCollapsed.value = !isCollapsed.value
      // 折叠时隐藏悬浮子菜单
      if (isCollapsed.value) {
        hideSubMenu()
      }
      // 触发全局事件通知其他组件侧边栏状态变化
      window.dispatchEvent(new CustomEvent('sidebar-collapse', { 
        detail: { collapsed: isCollapsed.value } 
      }))
    }

    // 显示悬浮子菜单
    const showSubMenu = (item, event) => {
      if (!isCollapsed.value) return
      clearHideTimer()
      activeSubMenu.value = item.name
      
      // 计算子菜单位置
      const target = event?.target?.closest('button') || event?.currentTarget
      if (target) {
        const rect = target.getBoundingClientRect()
        const menuWidth = 192 // w-48 = 12rem = 192px
        const menuHeight = Math.min(200, item.children ? item.children.length * 40 + 60 : 200) // 根据子项数量估算高度
        const padding = 16
        
        let left = rect.right + 8 // 默认在右侧
        let top = rect.top
        
        // 右侧超出屏幕时显示在左侧
        if (left + menuWidth > window.innerWidth - padding) {
          left = rect.left - menuWidth - 8
        }
        
        // 左侧仍然超出时居中显示
        if (left < padding) {
          left = Math.max(padding, (window.innerWidth - menuWidth) / 2)
        }
        
        // 顶部超出时调整
        if (top < padding) {
          top = padding
        }
        
        // 底部超出时向上调整
        if (top + menuHeight > window.innerHeight - padding) {
          top = Math.max(padding, window.innerHeight - menuHeight - padding)
        }
        
        // 最终安全检查，确保菜单完全在视口内
        left = Math.max(padding, Math.min(left, window.innerWidth - menuWidth - padding))
        top = Math.max(padding, Math.min(top, window.innerHeight - menuHeight - padding))
        
        subMenuPosition.value = { left: `${left}px`, top: `${top}px` }
      }
    }

    // 隐藏悬浮子菜单
    const hideSubMenu = () => {
      activeSubMenu.value = null
      clearHideTimer()
    }

    // 延迟隐藏悬浮子菜单
    const hideSubMenuDelayed = () => {
      clearHideTimer()
      hideTimer = setTimeout(() => {
        hideSubMenu()
      }, 300)
    }

    // 清除隐藏定时器
    const clearHideTimer = () => {
      if (hideTimer) {
        clearTimeout(hideTimer)
        hideTimer = null
      }
    }

    return {
      menuItems,
      ts,
      themeState,
      currentUser,
      limitedUserTypes,
      getUserTypeConfig,
      getUserIcon,
      quickSwitchUserType,
      showUserDemo,
      isCollapsed,
      toggleCollapse,
      expandedGroups,
      toggleGroup,
      isChildRouteActive,
      activeSubMenu,
      subMenuPosition,
      showSubMenu,
      hideSubMenu,
      hideSubMenuDelayed,
      clearHideTimer
    }
  }
}
</script>

<style scoped>
:deep() {
  user-select: text;
  -webkit-user-select: text;
  caret-color: transparent;
  cursor: default;
}

:deep(button) {
  cursor: pointer;
}

:deep(.policy-content) {
  ::selection {
    color: inherit;
  }
}

.glass-nav {
  transition: width 0.3s ease;
  position: relative;
}
</style>
